package utils;

import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 19242
 */
public class SqlToEsUtils {

    /**
     * where 后面条件
     * eg：where name = 'bb' and (class = 'c' or level = 'b') and age between 11 and 20 group by eid limit 1,5
     * @param sql
     * @return
     */
    public static String sqlToEs(String sql){
        if (StrUtil.isEmpty(sql)){
            throw new RuntimeException("不能为空");
        }
        // 将多个空格、\t、\n转换为一个空格
        sql = sql.replaceAll("\\s+", " ").trim();
        if (!sql.toUpperCase().startsWith("WHERE ")){
            throw new RuntimeException("开头为where");
        }
        sql = sql.substring(6);
        Name name = new Name(sql);
        List<String> queryList = new ArrayList<>();
        queryList.add("SearchSourceBuilder builder = new SearchSourceBuilder();");
        queryList.add(String.format("builder.query(new BoolQueryBuilder()%s);", name.desc()));
        return String.join("\n", queryList);
    }

    public static void main(String[] args) {
        // new BoolQueryBuilder().must(QueryBuilders.termQuery("name", "bb")).must(QueryBuilders.termQuery("name", "bb")).must(new BoolQueryBuilder())
        String where = sqlToEs(" where \t name = 'bb' or age = 11 and bb = 88 and c = 12\n ");
        System.out.println(where);
    }
}
